package com.demo.controller;


import com.demo.bean.Patent;
import com.demo.common.Result;
import com.demo.repositories.PatentRepository;
import com.demo.util.PatentUtil;
import org.apache.commons.io.FileUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.system.ApplicationHome;
import org.springframework.data.domain.Page;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;

import javax.servlet.http.HttpServletResponse;
import java.io.*;
import java.math.BigDecimal;
import java.net.URLEncoder;
import java.util.HashMap;
import java.util.List;
import java.util.Map;


@RestController
@RequestMapping("file")
public class FileController {
    @Autowired
    PatentRepository patentRepository;
    //    文件上传
    @RequestMapping("/fileUpload")
    @ResponseBody
    public Result fileUpload(MultipartFile file){
        ApplicationHome h = new ApplicationHome(getClass());
        System.out.println(file.getOriginalFilename());
        File jarF = h.getSource();
        System.out.println(jarF.getParentFile().toString());
        File dir=new File(jarF.getParentFile().toString()+File.separator+"upload");
//        if(!dir.exists()){
//            try {
//                dir.createNewFile();
//            } catch (IOException e) {
//                e.printStackTrace();
//            }
//
//        }
        InputStream inputStream=null;
        try {
            inputStream = file.getInputStream();
        } catch (IOException e) {
            e.printStackTrace();
        }
        long timestamp = System.currentTimeMillis();
        String[] split = file.getOriginalFilename().split("\\.");
        String type=split[split.length-1];
        String name=file.getOriginalFilename().substring(0,file.getOriginalFilename().indexOf(type)-1);
        System.out.println("name:  "+name+"  type:  "+type);
        String path=jarF.getParentFile().toString()+File.separator+"upload"+File.separator+timestamp+"."+type;
        System.out.println(path);
        File destFile=new File(path);
        try {
            FileUtils.copyInputStreamToFile(inputStream,destFile);
            //解析Xml文件
            Patent patent = PatentUtil.parseXml(path);
            List<Patent> patentList = patentRepository.getPageListByApplyNum(patent.getApplyNum());
            if(patentList!=null&&patentList.size()>0){
                for(int i=0;i<patentList.size();i++){
                    Patent oldPatent = patentList.get(0);
                    patentRepository.deleteById(oldPatent.getId());
                }
            }
            patentRepository.save(patent);
        } catch (IOException e) {
            e.printStackTrace();
        }
//        Double size=file.getSize()*1.0/1024/1024;
//        BigDecimal b   =   new   BigDecimal(size);
//        size=b.setScale(2,   BigDecimal.ROUND_HALF_UP).doubleValue();
//        Map param=new HashMap();
//        param.put("name",name);
//        param.put("type",type);
//        param.put("size",size+"M");
//        param.put("realName",timestamp);
//        System.out.println(param);

        return Result.ok().msg("上传成功");
    }



//    @GetMapping("/download")
//    public String downloadFile(@RequestParam("path")String path, HttpServletResponse response) {
//        ApplicationHome h = new ApplicationHome(getClass());
//        File jarF = h.getSource();
//
//
//        if (realName != null) {
//            //设置文件路径
//            File file = new File(path);
//            //File file = new File(realPath , fileName);
//            if (file.exists()) {
//                response.setContentType("application/force-download");// 设置强制下载不打开
//                response.setCharacterEncoding("utf-8");
//                try {
//                    name= URLEncoder.encode(name, "UTF-8").replaceAll("\\+", "%20");
//                } catch (UnsupportedEncodingException e) {
//                    e.printStackTrace();
//                }
////                response.setContentType("application/octet-stream");
//
//                // 将文件写入输入流
//                FileInputStream fileInputStream = null;
//                try {
//                    fileInputStream = new FileInputStream(file);
//                } catch (FileNotFoundException e) {
//                    e.printStackTrace();
//                }
//                InputStream fis = new BufferedInputStream(fileInputStream);
//                byte[] buffer = new byte[0];
//                try {
//                    buffer = new byte[fis.available()];
//                } catch (IOException e) {
//                    e.printStackTrace();
//                }
//                try {
//                    fis.read(buffer);
//                } catch (IOException e) {
//                    e.printStackTrace();
//                }
//                try {
//                    fis.close();
//                } catch (IOException e) {
//                    e.printStackTrace();
//                }
//
//// 清空response
//                response.reset();
//                try {
////                    fis = new FileInputStream(file);
////                    bis = new BufferedInputStream(fis);
//                    OutputStream outputStream = new BufferedOutputStream(response.getOutputStream());
//                    response.setContentType("application/octet-stream");
//                    response.addHeader("Content-Length", "" + file.length());
//                    // 设置文件头：最后一个参数是设置下载文件名
//                    response.setHeader("Content-disposition", "attachment;filename="+name+"."+type);
//                    outputStream.write(buffer);
//                    outputStream.flush();
//                    return "下载成功";
//                } catch (Exception e) {
//                    e.printStackTrace();
//                } finally { // 做关闭操作
//
//                    if (fis != null) {
//                        try {
//                            fis.close();
//                        } catch (IOException e) {
//                            e.printStackTrace();
//                        }
//                    }
//                }
//            }
//        }
//        return "下载失败";
//    }



}
